﻿using AutoMapper;
using B.S.BasicData.Api.Write.Applications.Command;
using B.S.BasicData.Domains;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructures;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.S.BasicData.Api.Write.Applications.CommandHandler
{
    public class AddUserRolePermissonCommandHandler : IRequestHandler<AddUserRolePermissonCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<UserInfos> userRepository;
        private readonly IBaseRepository<RoleUser> roleuserRepository;
        private readonly IBaseRepository<RolePermissons> rolepermissonRepository;
        private readonly IMapper mapper;
        private readonly ILogger<AddUserRolePermissonCommandHandler> logger;

        public AddUserRolePermissonCommandHandler(IBaseRepository<UserInfos> userRepository, IBaseRepository<RoleUser> roleuserRepository, IBaseRepository<RolePermissons> rolepermissonRepository, IMapper mapper, ILogger<AddUserRolePermissonCommandHandler> logger)
        {
            this.userRepository = userRepository;
            this.roleuserRepository = roleuserRepository;
            this.rolepermissonRepository = rolepermissonRepository;
            this.mapper = mapper;
            this.logger = logger;
        }

        public async Task<ApiResult<int>> Handle(AddUserRolePermissonCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            result.Code = ApiEnum.Success;
            result.Message = "添加用户-权限控制到功能级别成功";
            var count = await userRepository.GetAll().CountAsync(x => x.UserName == request.UserName);
            if (count > 0)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnum.Success,
                    Message = "该用户名已存在!!!",
                    data = -1
                };
            }
            using (var tran=userRepository.DB.Database.BeginTransaction())
            {
                try
                {
                   //用户表
                    logger.LogInformation("添加用户-权限控制到功能级别成功");
                    var entity = mapper.Map<UserInfos>(request);
                    await userRepository.Add(entity);
                    //用户角色表
                    var list = new List<RoleUser>();
                    foreach(var item in request.RoleIds)
                    {
                        list.Add(new RoleUser()
                        {
                            UserId = entity.UserId,
                            RoleId = item

                        });

                    }
                    await roleuserRepository.AddRange(list);
                    //中间表
                    var list2=new List<RoleUser>();
                    //提交
                    tran.Commit();
                }
                catch(Exception ex)
                {
                    tran.Rollback();
                }
            }
            return await Task.FromResult(result);
        }
    }
}
